import { BASE_API_URL } from "config/index";
import { showToast, ObjectToString } from "utils/index";
let showLoadTimer = null;
let loadingCount = 0;
const env = wx.getStorageSync("env") || getApp().globalData.env;
const startLoading = () => {
  wx.showLoading({
    title: "玩命加载中……",
    mask: true,
  });
};
const endLoading = () => {
  wx.hideLoading();
};
const showLoading = () => {
  if (loadingCount === 0) {
    showLoadTimer = setTimeout(() => {
      startLoading();
      showLoadTimer = null;
    }, 500);
  }
  loadingCount += 1;
};
const hideLoading = () => {
  if (loadingCount > 0) {
    loadingCount -= 1;
    if (loadingCount === 0) {
      if (showLoadTimer) {
        clearTimeout(showLoadTimer);
        showLoadTimer = null;
      } else {
        endLoading();
      }
    }
  }
};
//提示信息
const tipsMap = {
  404: { tip: "接口404", isShowToast: false },
};
//statusCode信息
const statusCodeMap = {
  400: { tip: "参数不匹配", isShowToast: false },
};
/**
 * 对wx.request二次封装处理
 * @param {string} method 请求方式。默认GET。可选值：OPTIONS，GET，HEAD，POST，PUT，DELETE，TRACE，CONNECT
 * @param {string} url 接口地址
 * @param {string/object/ArrayBuffer} data 传入的参数
 * @param {boolean} useLoad 是否使用loading提示
 * @param {object} other 和method、url、data、timeout同级的且除了它们之外的其他合法参数
 */
export default (
  method = "get",
  url = "",
  data = {},
  useLoad = true,
  other = {
    // header: {
    //   "content-type": "application/x-www-form-urlencoded",
    // },
  }
) => {
  useLoad && showLoading();
  if (!url.startsWith("http")) {
    url = BASE_API_URL[env] + url;
  }
  return new Promise((resolve, reject) => {
    wx.request({
      method,
      url,
      data,
      timeout: 10000,
      ...Object.assign(other, {
        //dataType: "json", //默认json
        header: {
          "content-type": "application/x-www-form-urlencoded;charset=utf-8", //解决小程序中文乱码导致参数不正确的问题
        },
        ...other,
      }),
      success(res) {
        let { cookies, data: resData, errMsg, header, statusCode } = res;
        if (statusCode === 200) {
          let { code, msg, result = null, data = null, message } = resData;
          //wx.hideLoading会关闭掉wx.showToast，造成后端返回的错误提示信息会一闪而过，因此需要分别在success、fail中分别调用wx.hideLoading
          useLoad && hideLoading();
          if (code === 200) {
            resolve(result || data || resData);
          } else {
            // let { tip, isShowToast = false } = tipsMap[code] || {};
            // if (isShowToast) {
            //   showToast(tip || msg || message);
            // } else {
            //   console.error(tip, resData);
            // }
            showToast(msg || message);
            reject(resData);
          }
        } else {
          console.error(statusCode + "：" + url);
          let { code, msg, result = null, data = null, message } = resData;
          showToast(msg || message);
          useLoad && hideLoading();
          reject(resData);
        }
      },
      fail(err) {
        const { errMsg, errno } = err;
        useLoad && hideLoading();
        console.error("请求错误：", err);
        if (errMsg.includes("timeout") || errMsg.includes("time out")) {
          showToast("请求超时");
        }
        reject(err);
      },
      complete(res) {
        // useLoad && hideLoading();
      },
    });
  });
};
